//package com.net.xpay.openapi.controller.openapi.paytrans;
//
//import com.google.common.base.Strings;
//import com.net.xpay.core.domain.AlipayUser;
//import com.net.xpay.core.domain.PayTrans;
//import com.net.xpay.core.domain.PayTransBatch;
//import com.net.xpay.core.domain.UserAccount;
//import com.net.xpay.core.manager.AlipayUserManager;
//import com.net.xpay.core.manager.PayTransBatchManager;
//import com.net.xpay.core.manager.PayTransManager;
//import com.net.xpay.core.manager.UserAccountManager;
//import com.net.xpay.core.model.PayTransBatchModel;
//import com.net.xpay.core.model.PayTransModel;
//import com.net.xpay.core.model.PayTransSearchModel;
//import com.net.xpay.core.model.UserTransLimitModel;
//import com.net.xpay.openapi.aop.OpenApi;
//import com.net.xpay.openapi.dto.*;
//import com.net.xpay.openapi.model.*;
//import com.net.xpay.openapi.protocol.OpenApiProtocol;
//import com.net.xpay.openapi.protocol.OpenApiResult;
//import com.net.common.concurrent.ThreadUtil;
//import com.net.common.exception.BusinessException;
//import com.net.xpay.openapi.dto.*;
//import com.net.xpay.openapi.model.*;
//import com.net.common.util.MoneyUtil;
//import com.net.common.util.SerializationUtil;
//import com.net.xpay.common.annotation.ApiMonitoring;
//import com.net.xpay.common.domain.User;
//import com.net.xpay.common.domain.openapi.OpenApp;
//import com.net.xpay.common.helper.NoticeHelper;
//import com.net.xpay.common.manager.UserManager;
//import com.net.xpay.common.manager.UserShardManager;
//import com.net.xpay.common.manager.openapi.OpenAppManager;
//import com.net.xpay.common.service.UserService;
//import com.net.xpay.core.constant.PoseidonErrorCode;
//import com.net.xpay.core.enums.PayTransBatchStatus;
//import com.net.xpay.core.helper.SignerCheckHelper;
//import com.net.xpay.core.service.OpenPayTransService;
//import com.net.xpay.core.utils.BeanCopierUtil;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.dao.DeadlockLoserDataAccessException;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.*;
//import java.util.List;
//
///**
// * 2020/6/28 09:46
//
// */
////@Controller
//@Slf4j
////@RequestMapping("/apiv1/openapi/pay-trans")
//@Api(tags = "第三方开放调用/批量有密", description = "第三方开放调用 批量有密 net")
//public class OpenApiPayTransController {
//
//    @Autowired
//    private OpenPayTransService openPayTransService;
//
//    @Autowired
//    private UserManager userManager;
//
//    @Autowired
//    private UserShardManager userShardManager;
//
//    @Autowired
//    private PayTransBatchManager payTransBatchManager;
//
//    @Autowired
//    private PayTransManager payTransManager;
//
//    @Autowired
//    private SignerCheckHelper signerCheckHelper;
//
//    @Autowired
//    private AlipayUserManager alipayUserManager;
//
//    @Autowired
//    private NoticeHelper noticeHelper;
//
//    @Autowired
//    private UserAccountManager userAccountManager;
//
//    @Autowired
//    private UserService userService;
//
//    @Autowired
//    private OpenAppManager openAppManager;
//
//    /**
//     * 查询余额 单位元 精确到2位小数
//     */
//    @OpenApi
//    @ApiMonitoring(value = "批量有密/查询服务费余额")
//    @ApiOperation(value = "查询服务费余额")
//    @ResponseBody
//    @PostMapping("/get-balance")
//    public OpenApiResult<OpenApiPayTransBalanceGetDto> getBalance(@RequestBody OpenApiProtocol openApiProtocol) {
//        OpenApiPayTransBalanceGetModel authModel = SerializationUtil.str2Object(openApiProtocol.getBizContent(), OpenApiPayTransBalanceGetModel.class);
//        OpenApp openApp = openAppManager.getById(Long.valueOf(openApiProtocol.getAppId()));
//        User user = userManager.getById(openApp.getUserId());
//
//        UserAccount userAccount = userAccountManager.getById(openApp.getUserId());
//        OpenApiPayTransBalanceGetDto dto = OpenApiPayTransBalanceGetDto.getInstance();
//        dto.setBalance(MoneyUtil.convertCentToString(userAccount.getMoneyLeft(), 2));
//
//        if (!Strings.isNullOrEmpty(authModel.getAlipayNickName())) {
//            dto.setAlipayNickName(authModel.getAlipayNickName());
//            AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(user.getId(), authModel.getAlipayNickName());
//            if (alipayUser == null) {
//                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "支付宝账号不存在");
//            }
//            UserTransLimitModel limit  = userService.getTransferLimit(user, alipayUser.getId());
//            dto.setDayTransMoney(limit.getCurrentDayTransLimit().toString());
//            dto.setMonthTransMoney(limit.getCurrentMonthTransLimit().toString());
//        }
//        return new OpenApiResult<>(dto);
//    }
//
//    /**
//     * 发起批量转账
//     */
//    @OpenApi
//    @ApiMonitoring(value = "批量有密/发起批量转账")
//    @ApiOperation("发起批量转账")
//    @PostMapping("/batch")
//    @ResponseBody
//    public OpenApiResult<OpenApiPayTransBatchDto> batchPayTrans(@RequestBody OpenApiProtocol openApiProtocol) {
//        OpenApiPayTransBatchModel payModel = SerializationUtil.str2Object(openApiProtocol.getBizContent(), OpenApiPayTransBatchModel.class);
//        OpenApp openApp = openAppManager.getById(Long.valueOf(openApiProtocol.getAppId()));
//        User user = userManager.getById(openApp.getUserId());
//        int retryCount = 0;
//        for (; ; ) {
//            try {
//                PayTransBatchModel payTransModel = new PayTransBatchModel();
//                BeanCopierUtil.copy(payModel, payTransModel);
//                payTransModel.setAppId(openApp.getId());
//
//                List<PayTransModel> payTrans = BeanCopierUtil.batchCopy(OpenApiPayTransModel.class, PayTransModel.class, payModel.getPayTrans());
//                payTransModel.setPayTrans(payTrans);
//                String payUrl = openPayTransService.batchPayTrans(user, payTransModel);
//
//                log.info("batchPayTrans success|importBatchNo={}", payModel.getImportBatchNo());
//                OpenApiPayTransBatchDto dto = new OpenApiPayTransBatchDto();
//                dto.setPayUrl(payUrl);
//                return new OpenApiResult<>(dto);
//            } catch (Exception e) {
//                if (e instanceof BusinessException) {
//                    throw e;
//                }
//                if (e instanceof DeadlockLoserDataAccessException) {
//                    log.warn("deadlock happen retry|payModel={}", SerializationUtil.obj2String(payModel), e);
//                    if (retryCount < 3) {
//                        retryCount++;
//                        ThreadUtil.safeSleep(100L, "");
//                        noticeHelper.sendSystemMonitorNotice("批量打款接口数据库发生死锁，开始重试次数：" + retryCount + "|" + payModel.getImportBatchNo(), "text");
//                        continue;
//                    }
//
//                }
//                log.warn("batchPayTrans unknown error|payModel={}|tryCount={}", SerializationUtil.obj2String(payModel), retryCount, e);
//                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "未知错误");
//            }
//        }
//
//    }
//
//
//    /**
//     * 关闭批次
//     */
//    @OpenApi
//    @ApiMonitoring(value = "批量有密/关闭批次")
//    @ApiOperation("关闭批次")
//    @PostMapping("/close-batch")
//    @ResponseBody
//    public OpenApiResult<OpenApiPayTransBatchCloseDto> closePayTransBatch(@RequestBody OpenApiProtocol openApiProtocol) {
//        OpenApiPayTransBatchCloseModel payModel = SerializationUtil.str2Object(openApiProtocol.getBizContent(), OpenApiPayTransBatchCloseModel.class);
//        OpenApp openApp = openAppManager.getById(Long.valueOf(openApiProtocol.getAppId()));
//        User user = userManager.getById(openApp.getUserId());
//
//        openPayTransService.closePayTransBatch(user, payModel.getImportBatchNo());
//        OpenApiPayTransBatchCloseDto dto = new OpenApiPayTransBatchCloseDto();
//        dto.setSuccess(true);
//        return new OpenApiResult<>(dto);
//    }
//
//    /**
//     * 查询转账批次结果
//     */
//    @OpenApi
//    @ApiMonitoring(value = "批量有密/查询转账批次结果")
//    @ApiOperation("查询转账批次结果")
//    @PostMapping("/query-pay-result")
//    @ResponseBody
//    public OpenApiResult<OpenApiPayTransPayResultQueryDto> queryPayResult(@RequestBody OpenApiProtocol openApiProtocol) {
//        OpenApiPayTransPayResultQueryModel queryModel = SerializationUtil.str2Object(openApiProtocol.getBizContent(), OpenApiPayTransPayResultQueryModel.class);
//        OpenApp openApp = openAppManager.getById(Long.valueOf(openApiProtocol.getAppId()));
//        User user = userManager.getById(openApp.getUserId());
//
//        if (Strings.isNullOrEmpty(queryModel.getImportBatchNo())) {
//            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "批次号不能为空");
//        }
//        PayTransBatch batch = payTransBatchManager.findByImportBatchNo(user.getId(), queryModel.getImportBatchNo());
//        if (batch == null) {
//            throw new BusinessException(PoseidonErrorCode.PAY_TRANS_BATCH_NOT_EXIST, "批次未上传成功");
//        }
//        OpenApiPayTransPayResultQueryDto dto = new OpenApiPayTransPayResultQueryDto();
//        BeanCopierUtil.copy(batch, dto);
//        //如果是最终状态 把批次详情也一起返回
//        if (PayTransBatchStatus.isFinalStatus(batch.getStatus())) {
//            List<PayTrans> payTransList = payTransManager.listByPayTransBatchId(user.getId(), batch.getId());
//            List<OpenApiPayTransDto> payTransDtos = BeanCopierUtil.batchCopy(PayTrans.class, OpenApiPayTransDto.class, payTransList);
//            dto.setPayTransList(payTransDtos);
//        }
//        return new OpenApiResult<>(dto);
//    }
//
//    /**
//     * 查询明细
//     */
//    @OpenApi
//    @ApiMonitoring(value = "批量有密/查询明细")
//    @ApiOperation("查询明细")
//    @PostMapping("/query-detail")
//    @ResponseBody
//    public OpenApiResult<OpenApiPayTransDetailQueryDto> queryDetail(@RequestBody OpenApiProtocol openApiProtocol) {
//        OpenApiPayTransDetailQueryModel queryModel = SerializationUtil.str2Object(openApiProtocol.getBizContent(), OpenApiPayTransDetailQueryModel.class);
//        OpenApp openApp = openAppManager.getById(Long.valueOf(openApiProtocol.getAppId()));
//        User user = userManager.getById(openApp.getUserId());
//
//        if (Strings.isNullOrEmpty(queryModel.getIdentity()) && Strings.isNullOrEmpty(queryModel.getImportBizNo())
//                && Strings.isNullOrEmpty(queryModel.getImportBatchNo())) {
//            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "收款方账号/订单编号/外部批次号 至少传其中一个参数");
//        }
//
//        PayTransSearchModel searchModel = new PayTransSearchModel();
//        searchModel.setUserId(user.getId());
//        searchModel.setImportBatchNo(queryModel.getImportBatchNo());
//        searchModel.setIdentity(queryModel.getIdentity());
//        searchModel.setImportBizNo(queryModel.getImportBizNo());
//        List<PayTrans> payTrans = payTransManager.list(searchModel);
//        List<OpenApiPayTransDetailQueryDto.OpenApiPayTransDto> payTransDtos = BeanCopierUtil.batchCopy(PayTrans.class, OpenApiPayTransDetailQueryDto.OpenApiPayTransDto.class, payTrans);
//
//        OpenApiPayTransDetailQueryDto dto = new OpenApiPayTransDetailQueryDto();
//        dto.setPayTransList(payTransDtos);
//        return new OpenApiResult<>(dto);
//    }
//}
